#region License
/*
Copyright (c) 2010, Dilyan Rusev
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list
 of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this 
list of conditions and the following disclaimer in the documentation and/or other 
materials provided with the distribution.

* Neither the name of TU-Sofia nor the names of its contributors may be used to endorse or 
promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace DbEngine
{
    /// <summary>
    /// Enumerates over a seqence of rows returend by SQLite
    /// </summary>
    /// <typeparam name="T">Persistent CLR type</typeparam>
    internal class DbEnumerator<T> : IEnumerator<T>
    {
        private System.Data.Common.DbDataReader dbReader;
        private DbTypeDefinition<T> dbTypeDef;

        /// <summary>
        /// Initializes a new instance of the <see cref="DbEnumerator&lt;T&gt;"/> class.
        /// </summary>
        /// <param name="dbReader">The db reader.</param>
        /// <param name="dbTypeDef">The db type definition.</param>
        public DbEnumerator(System.Data.Common.DbDataReader dbReader, DbTypeDefinition<T> dbTypeDef)
        {
            this.dbReader = dbReader;
            this.dbTypeDef = dbTypeDef;
        }

        /// <summary>
        /// Gets the element in the collection at the current position of the enumerator.
        /// </summary>
        /// <value></value>
        /// <returns>
        /// The element in the collection at the current position of the enumerator.
        /// </returns>
        public T Current
        {
            get
            {
                T instance = Activator.CreateInstance<T>();

                foreach (var dbField in this.dbTypeDef.Fields)
                {
                    var dbValue = this.dbReader[dbField.FieldName];
                    var prop = this.dbTypeDef.GetPropertyDesc(dbField.FieldName);
                    if (dbValue != null && dbValue.GetType() != prop.PropertyType)
                    {
                        var conv = TypeDescriptor.GetConverter(dbValue);
                        if (conv != null && conv.CanConvertTo(prop.PropertyType))
                        {
                            dbValue = conv.ConvertTo(dbValue, prop.PropertyType);
                        }
                        else
                        {
                            throw new InvalidCastException(string.Format("Property {0} of type {1} is mapped to db field {2}, which is of type {3} and there is no possible convertion",
                                prop.Name, prop.PropertyType, dbField.FieldName, dbField.DbType));
                        }
                    }
                    prop.SetValue(instance, dbValue);
                }

                return instance;
            }
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            if (this.dbReader != null) this.dbReader.Dispose();
        }

        /// <summary>
        /// Gets the element in the collection at the current position of the enumerator.
        /// </summary>
        /// <value></value>
        /// <returns>
        /// The element in the collection at the current position of the enumerator.
        /// </returns>
        object System.Collections.IEnumerator.Current
        {
            get { return this.Current; }
        }

        /// <summary>
        /// Advances the enumerator to the next element of the collection.
        /// </summary>
        /// <returns>
        /// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
        /// </returns>
        /// <exception cref="T:System.InvalidOperationException">
        /// The collection was modified after the enumerator was created.
        /// </exception>
        public bool MoveNext()
        {
            return this.dbReader.Read();
        }

        /// <summary>
        /// Sets the enumerator to its initial position, which is before the first element in the collection.
        /// </summary>
        /// <exception cref="T:System.InvalidOperationException">
        /// The collection was modified after the enumerator was created.
        /// </exception>
        public void Reset()
        {
            throw new NotSupportedException();
        }
    }
}
